package com.ruikong.dazhi.service.impl.baseinfo;

import com.github.pagehelper.PageException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruikong.dazhi.controller.result.BaseResult;
import com.ruikong.dazhi.controller.result.ResultApi;
import com.ruikong.dazhi.dao.basicinfo.ProductMapper;
import com.ruikong.dazhi.dao.basicinfo.StockMapper;
import com.ruikong.dazhi.entity.basicinfo.Product;
import com.ruikong.dazhi.entity.basicinfo.ProductRecipe;
import com.ruikong.dazhi.dao.basicinfo.ProductRecipeMapper;
import com.ruikong.dazhi.entity.basicinfo.Stock;
import com.ruikong.dazhi.model.input.ProductRecipePageInput;
import com.ruikong.dazhi.model.output.ProductRecipeOutput;
import com.ruikong.dazhi.service.basicinfo.IProductRecipeService;
import com.ruikong.dazhi.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * (ProductRecipe)表服务实现类
 *
 * @author makejava
 * @since 2021-11-11 15:39:02
 */
@Service("productRecipeService")
public class IProductRecipeServiceImpl implements IProductRecipeService {
    @Resource
    private ProductRecipeMapper productRecipeMapper;


    @Resource
    private ProductMapper productMapper;

    @Resource
    private StockMapper stockMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ProductRecipe queryById(Integer id) {
        return this.productRecipeMapper.queryById(id);
    }


    /**
     * 新增数据
     *
     * @param productRecipe 实例对象
     * @return 实例对象
     */
    @Override
    public int insert(ProductRecipe productRecipe) {
       productRecipe.setIsDeleted(0);

        return   this.productRecipeMapper.insert(productRecipe);
    }

    /**
     * 修改数据
     *
     * @param productRecipe 实例对象
     * @return 实例对象
     */
    @Override
    public int update(ProductRecipe productRecipe) {
     return    this.productRecipeMapper.update(productRecipe);

    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.productRecipeMapper.deleteById(id) > 0;
    }

    @Override
    public PageInfo<ProductRecipeOutput> getRecipePageInfo(ProductRecipePageInput input) {
        PageHelper.startPage(input.getPageNumber(),input.getPageSize());
        List<ProductRecipeOutput> productRecipeOutputList=this.productRecipeMapper.selectByProductId(input.getProductId());
        if (productRecipeOutputList!=null && productRecipeOutputList.size()>0){
            //加上总比例值
            double total=this.productRecipeMapper.totalRate(input.getProductId());
            ProductRecipeOutput productRecipeOutput=new ProductRecipeOutput();
            productRecipeOutput.setRate(String.valueOf(total));
            productRecipeOutput.setId(-1);
            productRecipeOutputList.add(productRecipeOutput);
        }
        PageInfo pageInfo=new PageInfo(productRecipeOutputList);
        return pageInfo;
    }

    @Override
    public BaseResult recipeImport(MultipartFile multipartFile) {
        BaseResult baseResult=  new BaseResult();
        try {
            //将multipartFileToFile转化为File
            File file = ExcelUtil.multipartFileToFile(multipartFile);
            InputStream inputStream = new FileInputStream(file);
            String fileName = file.getName();
            String suffix = fileName.split("\\.")[1];
            int productId=0;
            //存放产品集合用于批次保存
            List<ProductRecipe> productRecipes=new ArrayList<>();
            if (!suffix.equals("xlsx") && !suffix.equals("xls")) {
                baseResult.setMsg("错误！提交文件格式不正确，请上传excel文件");
                baseResult.setCode(ResultApi.failCode);
                return baseResult;
            }
            //xlsx文件使用XSSFWorkbook，否则使用HSSFWorkbook
            Workbook workbook = suffix.equals("xlsx") ? new XSSFWorkbook(inputStream) : new HSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            Cell cell = null;
            Row row = null;
            Iterator<Row> iterator = sheet.rowIterator();
            int index = 0;
            while (iterator.hasNext()) {
                row = iterator.next();
                //跳过第一行标题行
                if (0 == index) {
                    index++;
                    continue;
                }

                //新建产品配方对象
                ProductRecipe productRecipe=new ProductRecipe();
                productRecipe.setIsDeleted(0);


                //正则表达式判断是否在正数
                Pattern p=Pattern.compile("^(([0-9]+\\\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\\\.[0-9]+)|([0-9]*[1-9][0-9]*))$");

                Matcher matcher;
                //产品编号
                cell = row.getCell(0);
                String productSn;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，产品编号不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {

                    cell.setCellType(CellType.STRING);
                    productSn = cell.getStringCellValue().trim();
                    //通过产品编号查询产品信息
                    Product  product=this.productMapper.selectByProductSn(productSn);
                    if (product==null){
                        baseResult.setMsg(String.format("错误！表格第%s行，系统中不存在该编号的产品",index+1));
                        baseResult.setCode(ResultApi.failCode);
                        file.delete();
                        return baseResult;
                    }
                    productId=product.getId();
                    productRecipe.setProductId(product.getId());
                }


                //原料编号
                cell = row.getCell(1);
                String stockSn;
                if (cell == null || cell.getCellTypeEnum() == CellType.BLANK) {
                    baseResult.setMsg(String.format("错误！表格第%s行，原料编号不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    stockSn = cell.getStringCellValue().trim();
                    //通过原料编号查询原料信息
                    Stock stock=this.stockMapper.selectByStockSn(stockSn);
                    if (stock==null){
                        baseResult.setMsg(String.format("错误！表格第%s行，系统中不存在该编号的原料",index+1));
                        baseResult.setCode(ResultApi.failCode);
                        file.delete();
                        return baseResult;
                    }
                    productRecipe.setStockId(stock.getId());
                }

                //占比
                cell = row.getCell(2);
                Float  rate;
                if (cell==null|| cell.getCellTypeEnum() == CellType.BLANK){
                    baseResult.setMsg(String.format("错误！表格第%s行，占比不能为空", index + 1));
                    baseResult.setCode(ResultApi.failCode);
                    file.delete();
                    return baseResult;
                }
                if (cell != null) {


                    cell.setCellType(CellType.STRING);
                    String rateStr=cell.getStringCellValue();
                   matcher=p.matcher(rateStr);
                    if (!matcher.matches()){
                        baseResult.setMsg(String.format("错误！表格第%s行，占比请输入正数", index + 1));
                        baseResult.setCode(ResultApi.failCode);
                        file.delete();
                        return baseResult;
                    }
                    else {
                        rate=Float.valueOf(rateStr);
                        if (rate<0||rate>100){
                            baseResult.setMsg(String.format("错误！表格第%s行，占比必须在0~100之间", index + 1));
                            baseResult.setCode(ResultApi.failCode);
                            file.delete();
                            return baseResult;
                        }
                        else {
                            productRecipe.setRate(rate);
                        }
                    }

                }
                //误差值
                cell = row.getCell(3);
                Float errorNumber=0f;
                if (cell==null || cell.getCellTypeEnum()==CellType.BLANK){
                    errorNumber=2.0f;
                }
                else {
                    cell.setCellType(CellType.STRING);
                    String errorStr=cell.getStringCellValue();
                    matcher=p.matcher(errorStr);
                    if (!matcher.matches()){
                        baseResult.setMsg(String.format("错误！表格第%s行，误差值请输入正数", index + 1));
                        baseResult.setCode(ResultApi.failCode);
                        file.delete();
                        return baseResult;
                    }
                    errorNumber=Float.valueOf(errorStr);
                }
                productRecipe.setErrorNumber(errorNumber);
                productRecipes.add(productRecipe);
            }
            //先删除原有配方数据
            productRecipeMapper.deleteByProductId(productId);
            productRecipes.stream().forEach(x->this.productRecipeMapper.insert(x));
            file.delete();
            baseResult.setMsg("导入成功");
            baseResult.setCode(ResultApi.successCode);
        }catch (Exception e){
            baseResult.setMsg("配方导入时出错");
            baseResult.setCode(ResultApi.errorCode);
            e.printStackTrace();
        }
        return baseResult;
    }




}
